<template>
  <div id="spreadRoot" class="bg-2F3843 c-flex-column">
    <div class="c-br20 c-flex-center c-flex-row c-flex-grow1 c-h0 c-p">
      <div @click="clickGoBack" class="c-ww50 c-hh50 c-flex-row c-flex-center c-pa c-p-t24 c-p-l24 c-brp50 c-opacity80 c-bg-black">
        <i class="iconfont c-fc-white c-fs20">&#xe600;</i>
      </div>
      <div id="spreadImg" class="c-w100 c-h c-pv20 c-ph100 c-flex-row c-flex-center">
        <img class="c-w100 c-br20 app-save-img" :src="posterImage" alt />
      </div>
    </div>
    <footer class="c-bg-white c-hh180 c-bd-t1 c-w100 c-ph24">
      <p class="c-flex-row c-aligni-center c-fs20 c-fc-sblack c-mt20 c-mb20">
        <span class="c-flex-grow1 c-w0">长按上面图片保存海报</span>
        <span @click="clickMoreShare" class="theme-fc">更多邀请方式</span>
      </p>
      <section class="c-contexty-hidden c-contextX-scroll c-ws-n" style="overflow:auto" id="scroll">
        <div v-for="item in posterImgList" :key="item.id" @click="clickSetPoster(item.id)" class="c-p c-mr20 c-inlineblack c-hh100 c-ww100">
          <img class="c-h c-w100 c-br10 img-pe-none" :src="$addXossFilter(item.image)" />
          <div v-show="curImgId == item.id" class="c-flex-row c-flex-center c-pa c-p-b6 c-p-r6 c-brp50 c-ww30 c-hh30 theme-bg c-bd1-white">
            <i class="iconfont c-fc-white c-fs16">&#xe76c;</i>
          </div>
        </div>
      </section>
    </footer>
    <div class="masker img-pe-none" v-if="isShowMasker"></div>
    <cj-popup v-model="showMoreShareModal" round closeable position="bottom">
      <article class="c-w100 c-ph100 c-textAlign-c">
        <div class="c-fs28 c-fw-b c-pt30">邀请方式</div>
        <div class="c-fs24 c-fc-xblack c-pt20 c-pb40">
          点击微信右上角三个点 “…”通过【发送给朋友】【分享到朋友圈】推广
        </div>
      </article>
    </cj-popup>
  </div>
</template>

<script>
import { Json2canvas } from '@/utils/json2image.js';
import { getAgentJson } from '@/utils/canvasJson/agentPosterJson.js';
import { utilJs } from '@/utils/common.js';
const FROM_PAGE_ENUM = {
  AGENT: 1, //来自服务商
  SHARE_HOLDER: 2 //来自股东
};
const AGENT_WORD_MAP = {
  0: '加入我们，让创业更简单',
  1: '邀您一起成为知识的传播者',
  2: '给自己一个机会，推开知识的大门'
};
const SHARE_HOLDER_WORD_MAP = {
  0: '诚邀您一起成为店铺股东',
  1: '加入我们，共创未来',
  2: '加入我们，一起赚大钱'
};
export default {
  name: 'spreadAgent',
  data() {
    return {
      showMoreShareModal: false,
      FROM_PAGE_ENUM: FROM_PAGE_ENUM,
      fromPage: FROM_PAGE_ENUM.AGENT,
      posterImgList: [],
      curImgId: '',
      posterImage: '',
      isShowMasker: false
    };
  },
  created() {
    utilJs.appShare(this);
  },
  methods: {
    // 设置大小
    initJson2image() {
      this._json2image = new Json2canvas();
    },
    // 销毁
    destroyJson2image() {
      if (this._json2image) {
        this._json2image.destroy();
      }
    },
    async clickSetPoster(imgId) {
      console.time('clickSetPosterStart');
      if (!this._json2image) {
        return;
      }
      let curInfo = this._posterList.find(i => i.id == imgId);
      this.posterImage = curInfo.image;
      if (!curInfo) {
        return;
      }
      this.curImgId = imgId;
      if (this._drawedPosterMap[imgId]) {
        this.posterImage = this._drawedPosterMap[imgId];
        return;
      }
      let data = [];
      let res = '';
      try {
        this.isShowMasker = true;
        this.$loading.show({
          text: '邀请卡生成中'
        });
        document.ontouchstart = null;
        document.ontuchmove = null;
        document.ontouchend = null;
        await this._json2image.init();
        data = getAgentJson(curInfo, this._json2image);
        console.log('---json--', data);
        console.time('initJson');
        await this._json2image.initJson(data);
        console.timeEnd('initJson');
        console.time('startDraw');
        await this._json2image.startDraw();
        console.timeEnd('startDraw');
        console.time('toDataUrl');
        res = await this._json2image.toDataUrl();
        console.timeEnd('toDataUrl');
      } catch (error) {
        console.log('err', error);
        this.$loading.hide();
        this.isShowMasker = false;
      }
      if (!res) {
        this.$loading.hide();
        this.isShowMasker = false;
        return;
      }

      this._drawedPosterMap[imgId] = res;
      document.ontouchstart = true;
      document.ontuchmove = true;
      document.ontouchend = true;
      this.posterImage = res;
      this.$nextTick(() => {
        this.isShowMasker = false;
        this.$loading.hide();
        console.timeEnd('clickSetPosterStart');
      });
    },
    clickMoreShare() {
      this.showMoreShareModal = true;
    },
    clickGoBack() {
      this.$router.go(-1);
    },
    getSpreadInfo() {
      let getUrl = `${global.apiurl}common/promotionImages?ckFrom=${this.fromPage}`;
      utilJs.getMethod(getUrl, res => {
        this.customName = JSON.parse(localStorage.getItem('customName'));
        this._shareholderName = res.shareholderName; //股东名称
        setDocumentTitle(`${this.fromPage == FROM_PAGE_ENUM.AGENT ? this.customName.serviceProviderName : this.fromPage == FROM_PAGE_ENUM.SHARE_HOLDER ? this._shareholderName : ''}海报`);
        let posterList = res.images.filter(i => i.status == 1 && i.initSort < 9);
        const posterListLength = posterList.length;
        this.wechatShare();
        if (!posterListLength) {
          this.$showCjToast({
            text: '没有可分享的海报',
            type: 'warn',
            time: 1000
          });
          return;
        }
        const companyLogo = localStorage.getItem('shareLogo');
        const companyAuth = JSON.parse(localStorage.getItem('companyAuth'));
        //填充底部图片列表和每个海报数据
        let imageList = [];
        for (let item of posterList) {
          item.avatar = res.avatar;
          item.nickname = res.nickname;
          item.qrcodeImg = res.qrcodeImg;
          item.companyLogo = companyLogo;
          item.companyAuth = companyAuth;
          item.wordText = this.fromPage == FROM_PAGE_ENUM.AGENT ? AGENT_WORD_MAP[item.wordId] : SHARE_HOLDER_WORD_MAP[item.wordId];
          imageList.push({
            id: item.id,
            image: item.image
          });
        }
        this._posterList = posterList;
        this.posterImgList = imageList;
        this.curImgId = imageList[0].id;
        this.clickSetPoster(this.curImgId);
      });
    },
    setShareConfig() {
      let title = `升级${this.fromPage == FROM_PAGE_ENUM.SHARE_HOLDER ? this._shareholderName : this.customName.serviceProviderName}`;
      let shareImg = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/common/provider.png';
      let shareUrl = window.location.href.split('#')[0] + '#/homePage/agent/agentIndex?' + '&refereeId=' + localStorage.getItem('userId');
      let shareDesc = '点击查看详情';
      if (this.fromPage == FROM_PAGE_ENUM.SHARE_HOLDER) {
        shareUrl += '&fromType=shareholder';
        if (localStorage.getItem('shareholderId')) {
          shareUrl += '&shareholderId=' + localStorage.getItem('shareholderId');
        }
      }
      return { title, shareImg, shareUrl, shareDesc };
    },
    //分享
    wechatShare: function() {
      const { shareUrl, title, shareImg, shareDesc } = this.setShareConfig();
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function() {});
    },
    // //手机端分享
    appShare: function() {
      const { shareUrl, title, shareImg, shareDesc } = this.setShareConfig();
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },
  mounted() {
    //如果是ios,则去掉minHeight设置，防止底部前进后退导航挡住页面
    if (utilJs.isIosWechat()) {
      document.getElementById('spreadRoot').style.minHeight = '';
      document.getElementById('spreadRoot').style.height = '100%';
    }
    this.fromPage = this.$route.query.ckFrom || FROM_PAGE_ENUM.AGENT;
    setDocumentTitle('海报');
    this._json2image = null;
    this._shareholderName = '';
    this._posterList = [];
    this._drawedPosterMap = {};
    this.getSpreadInfo();
    this.initJson2image();
  },
  beforeDestroy() {
    this.$loading.hide();
    this.destroyJson2image();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#spreadRoot {
  min-height: auto;
  height: 100%;
  overflow: hidden;
}
.bg-2F3843 {
  background-color: #2f3843;
}

.masker {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  background: #fff;
  opacity: 0.5;
}
.check {
  top: calc(50% - 0.4rem);
  left: calc(50% - 0.4rem);
}
</style>
